//
//  USAskListViewController.m
//  us
//
//  Created by lhx on 2025/5/7.
//

#import "USAskListViewController.h"
#import "USAskListTableViewCell.h"
#import "USAskDetailViewController.h"
#import <MJRefresh/MJRefresh.h>

#import "TearOpenView.h"

@interface USAskListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray <USTalkModel *>*talkModelList;

@property (nonatomic, strong) USTalkModel *todayTalkModel;//用于判断是否有未领取的今日问答
@property (nonatomic, strong) TearOpenView *openView;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) BOOL hasMore;

@end

@implementation USAskListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"问答";

    self.displayEmptySet = NO;
    [self setupView];
    [self setupRefresh];
    [self.us_tableView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.us_tableView.mj_header beginRefreshing];

}
- (void)setupView {
    
    self.us_tableView.delegate = self;
    self.us_tableView.dataSource = self;
    self.us_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.us_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.us_tableView.backgroundColor = UIColor.clearColor;
    
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USAskListTableViewCell" bundle:nil] forCellReuseIdentifier:@"USAskListTableViewCellId"];

}
- (void)setOpenViewState {
    
    if (self.todayTalkModel && self.todayTalkModel.talkState == 0) {
        
        self.openView.hidden = NO;
        
        [self.us_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-16 - 100);
        }];
    }else{
        if (self.openView) {
            self.openView.hidden = YES;
        }
        [self.us_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.mas_offset(0);
        }];
    }

}

- (void)setupRefresh {
    self.currentPage = 1;
    self.pageSize = 15;
    
    @weakify(self)
    self.us_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
     @strongify(self)
        self.currentPage = 1;
        [self updateAskList];
        [self getTodayTalkState];
    }];
    
    self.us_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        if (self.hasMore) {
            self.currentPage += 1;
            [self updateAskList];
        } else {
            [self.us_tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}

- (TearOpenView *)openView {
    if (_openView == nil) {
        TearOpenView *openView = [[TearOpenView alloc]initWithFrame:CGRectMake(16, 100, self.view.jk_width - 16 * 2, 93)];
        openView.contentLab.text = self.todayTalkModel.talkTitle;
        _openView = openView;
        openView.hidden = YES;
        [self.view addSubview:openView];
        @weakify(self)
        @weakify(openView)
        openView.tearCompletedBlock = ^{
            @strongify(self)
            @strongify(openView)
            [USFeedbackTool impactSoft];
            
            USAskDetailViewController *vc = [USAskDetailViewController new];
            vc.talkModel = self.todayTalkModel;
            [self.navigationController pushViewController:vc animated:YES];
            
            [openView removeFromSuperview];
            
            [self.us_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
                make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
                make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.bottom.mas_equalTo(0);
            }];
        };
        
        openView.didReachBottomBlock = ^{
            @strongify(self)
            [self getTodayTalk];
        };
        [openView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(16);
            make.right.mas_offset(-16);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-16);
            make.height.mas_equalTo(93);
        }];
        
    }
    return _openView;
}

- (void)updateAskList{
    NSDictionary *params = @{ @"current": @(self.currentPage),
                              @"size": @(self.pageSize)};
    
    [[EMNetWork shareManager] em_post:API_DailyTalkListPage
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        if (self.currentPage == 1) {
            [self.talkModelList removeAllObjects];
        }
        
        NSArray *records = [USTalkModel mj_objectArrayWithKeyValuesArray:api.data[@"dailyTalkList"][@"records"]];
        
        [self.talkModelList addObjectsFromArray:records];
        // 是否还有更多
        self.hasMore = records.count == self.pageSize;
        
        // 结束刷新状态
        [self.us_tableView.mj_header endRefreshing];
        [self.us_tableView.mj_footer endRefreshing];
        
        if (!self.hasMore) {
            [self.us_tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.us_tableView.mj_footer resetNoMoreData];
        }
        
        if (self.talkModelList.count == 0) {
            self.dataState = EmptyDataStateNoData;
        }
        self.us_tableView.mj_footer.hidden = self.talkModelList.count == 0;
        
        [self.us_tableView reloadData];
        [self.us_tableView reloadEmptyDataSet];
        
    } fail:^{
        
        
    }];
    
}

///今日问答领取状态
- (void)getTodayTalkState {
    @weakify(self)
    [[EMNetWork shareManager] em_post:API_DailyTalkToday
                               params:nil
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (!api.success) {
            return;
        }
        USTalkModel *model = [USTalkModel mj_objectWithKeyValues:api.data];
        self.todayTalkModel = model;

        
        [self setOpenViewState];

    } fail:^{
        
        
    }];
}

- (void)getTodayTalk {
    [[EMNetWork shareManager] em_post:API_DailyTalkGetToday
                               params:@{@"sysDailyTalkId":self.todayTalkModel.sysDailyTalkId?:@""}
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
        if (!api.success) {
            return;
        }
        USTalkModel *model = [USTalkModel mj_objectWithKeyValues:api.data[@"dailyTalk"]];
        self.todayTalkModel = model;
        
        [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_GetTalk andExt:@{}];
    } fail:^{
        
        
    }];
}

- (NSMutableArray <USTalkModel *>*)talkModelList {
    if (_talkModelList == nil) {
        _talkModelList = [NSMutableArray array];
    }
    return _talkModelList;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [USFeedbackTool impactSoft];

    USTalkModel *model = self.talkModelList[indexPath.row];

    USAskDetailViewController *vc = [[USAskDetailViewController alloc]init];
    vc.talkModel = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.talkModelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    USAskListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USAskListTableViewCellId"];

    USTalkModel *model = self.talkModelList[indexPath.row];
    
    if (model.completionStatus == 0) {
        cell.loveImgView.image = [[UIImage imageNamed:@"ic_love_red"] imageWithTintColor:[UIColor jk_colorWithHex:0x212121 andAlpha:0.2]];
        cell.numLab.textColor = [UIColor jk_colorWithHex:0x212121 andAlpha:0.2];
    }else {
        cell.loveImgView.image = [[UIImage imageNamed:@"ic_love_red"] imageWithTintColor:[UIColor jk_colorWithHex:0xD55757]];
        cell.numLab.textColor = [UIColor jk_colorWithHex:0x212121];
    }
    cell.contentLab.text = model.talkTitle;
    cell.numLab.text = [NSString stringWithFormat:@"Q%li",model.seq];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

 

@end
